package com.stadium.service.impl;


import com.stadium.common.config.security.TokenAuthentication;
import com.stadium.dto.LoginDto;
import com.stadium.dto.SysUserDto;
import com.stadium.service.SysLoginSV;
import com.stadium.vo.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * @program: smartgame-rugby
 * @description:
 * @author: firstSeven
 * @create: 2020/01/19
 */
@Service
@Transactional
public class SysLoginSVI implements SysLoginSV {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenAuthentication tokenAuthentication;

    @Override
    public LoginDto login(LoginVo loginVO, SysUserDto sysUserDto) {
        LoginDto loginDto = new LoginDto();
        String token = getLoginInfo(sysUserDto);
        loginDto.setToken(String.valueOf(token));
        loginDto.setSysUserDto(sysUserDto);
        return loginDto;
    }

    private String getLoginInfo(SysUserDto sysUserDto) {
        // 把需要放的信息置入UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUserDto.getId() + "," + sysUserDto.getName() + "," + sysUserDto.getIdNumber() + "," + sysUserDto.getPhoneNum(), sysUserDto.getPassword());
        // 把tocken令牌置入auth管理，也就是调用CustomAuthenticationProvider
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        // 调用创建jwt
        String token = tokenAuthentication.createToken(authentication);
        return token;
    }

}
